28

Beginner’s Guide to Code Algorithms

28

STEP 3

If Not ComputerPlayed Then

Call FIndBestOption(OScore, BestCell)

End If

A = ExamineEachFormCell(EmptyX, EmptyY, EmptyCount, OScore, XScore)

'EmptyCount = NextEmptyFormCell(EmptyX, EmptyY, OScore, XScore)

End Sub

Sub FIndBestOption(OScore, BestCell)

Factor(1) = Array(0, 2, 3, 5)

Factor(2) = Array(0, 7, 11, 13)

Factor(3) = Array(0, 17, 19, 23)

BestCell = 0

MaxPossibility = 0

For k = 1 To 8

Possibility = 0

For i = 1 To 3

For j = 1 To 3

If UserForm1.Controls("TextBox" & (i - 1) * 3 + j) = "" Then

If BestCell = 0 Then

BestCell = (i - 1) * 3 + j

End If

If WorksheetFunction.Gcd(WinTag(k), Factor(i)(j) * OScor e) > 1 Then

Possibility = Possibility + 1

If MaxPossibility < Possibility Then

MaxPossibility = Possibility

BestCell = (i - 1) * 3 + j

End If

End If

End If

Next

Next

Next

If BestCell > 0 Then

UserForm1.Controls("TextBox" & BestCell) = "O"

End If

End Sub

FIGURE 2.25  Continued

2.5  UNDERSTANDING THE NEED FOR AN ALGORITHM

When playing Tic Tac Toe, we see the winning line pretty easily:

• Any row

• Any column

• Any diagonal

With the same symbol (noughts or crosses)

But the computer cannot see the pattern that easily.

We already have a defined way to identify each of the nine cells in the game.

This is by the use of a row number (1–​3) and a column number (1–​3).

And we already know how to figure out the exact placement of noughts and crosses

on the board.